package com.anrongtec.zcpt.tab02;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseFragment;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.listener.AppBarStateChangeListener;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.BannerApp;
import com.anrongtec.zcpt.module.FileId;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.SnackbarUtil;
import com.anrongtec.zcpt.util.Util;
import com.anrongtec.zcpt.view.VerticalSwipeRefreshLayout;
import com.art.base.util.ApkUtils;
import com.art.base.util.AppCacheUtils;
import com.art.base.util.FileUtils;
import com.art.base.util.ToastShow;
import com.art.base.util.log.LogUtil;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 
 * @author cxy
 *
 */
public class TabSecondFragment extends BaseFragment {

	private ViewPager viewPager;
	private RecyclerView rv_latest, rv_download, rv_comment;
	private TabLayout tabLayout;
	private Banner banner;
	private AppBarLayout appbarLayout;

	private String[] tabName;
	private CommonAdapter<AppModel> adapter;
	/** 最新上线, 下载最多, 好评最多 */
	private List<AppModel> latest, download, comment;

	private Intent intent;

	/** 当前查询页 */
	private int page = 1;
	private PagerAdapter pagerAdapter;
	/** banner */
	private ArrayList<String> imageUrls;
	private VerticalSwipeRefreshLayout swipe_refresh;
	/** 加载页面 */
	private View loading;
	/** 消失动画 */
	private Animation out;

	private static final String CACHE_BANNER = "banner";

	private OnBannerClickListener bannerListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_tab_second, null);
		// View v = inflater.inflate(R.layout.default_loading, null);

		initViews(v);

		return v;
	}

	@Override
	protected void initViews(View view) {
		super.initViews(view);
		initLoading(view);
		initSwipeRefresh(view);
		initAppBarLayout(view);
		initData();
		initRecyclerView(view);
		initViewPager(view);
		initTabLayout(view);
		initBanner(view);
	}

	/**
	 * 初始化加载页面
	 * 
	 * @param view
	 */
	private void initLoading(View view) {
		loading = view.findViewById(R.id.loading);
		out = AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out);
	}

	/**
	 * 初始化appbarlayout
	 */
	private void initAppBarLayout(View view) {
		appbarLayout = (AppBarLayout) view.findViewById(R.id.appbarlayout_tab02);
		appbarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
			@Override
			public void onStateChanged(AppBarLayout appBarLayout, State state) {
				if (state == State.EXPANDED) {
					// TODO 禁用下拉刷新 展开状态
					swipe_refresh.setEnabled(true);
				} else if (state == State.COLLAPSED) {
					// 折叠状态
					swipe_refresh.setEnabled(false);
				} else {
					// 中间状态

				}
			}
		});
	}

	/**
	 * 初始化下拉刷新
	 * 
	 * 
	 * @param view
	 */
	private void initSwipeRefresh(View view) {
		swipe_refresh = (VerticalSwipeRefreshLayout) view.findViewById(R.id.swipe_tab02_refresh);
		swipe_refresh.setColorSchemeResources(android.R.color.holo_blue_bright);
		swipe_refresh.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				getApps(URLConstants.SORT_LATEST, page);
				getApps(URLConstants.SORT_DOWNLOAD, page);
				getApps(URLConstants.SORT_COMMENT, page);
				getBanners();
			}
		});
	}

	/**
	 * 设置BannerView数据源
	 */
	private void initBanner(View view) {
		banner = (Banner) view.findViewById(R.id.bv_tab02_banner);
		banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
		banner.setIndicatorGravity(BannerConfig.RIGHT);

		// 拿缓存地址先显示
		ArrayList<String> images = (ArrayList<String>) AppCacheUtils.getInstance(getActivity(), CACHE_BANNER)
				.getObject(CACHE_BANNER);
		banner.setImages(images);

		imageUrls = new ArrayList<String>();
		// 再获取最新banner信息显示
		getBanners();
	}

	@Override
	protected void initData() {
		tabName = new String[] { "最新上线", "下载最多", "好评最多" };
		latest = new ArrayList<AppModel>();
		download = new ArrayList<AppModel>();
		comment = new ArrayList<AppModel>();

		// 获取app信息
		getApps(URLConstants.SORT_LATEST, page);
		getApps(URLConstants.SORT_DOWNLOAD, page);
		getApps(URLConstants.SORT_COMMENT, page);
	}

	/**
	 * 联网获取banner信息
	 */
	private void getBanners() {
		String json = GsonUtil.toBannerJson();
		HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
			@Override
			public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
				super.onResponse(arg0, arg1, arg2, arg3);
				JsonDataRestult<PageList<FileId>> result = GsonUtil.decode(arg1,
						new TypeToken<JsonDataRestult<PageList<FileId>>>() {
						}.getType());
				if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
					final ArrayList<FileId> carousels = result.getData().getCarousels();
					if (Util.isEmpty(carousels)) {
						LogUtil.trace(Log.DEBUG, "TAB02", "banner is empty");
						return;
					}
					imageUrls.clear();
					for (int i = 0; i < carousels.size(); i++) {
						imageUrls.add(carousels.get(i).getFileId());
					}
					// imageUrls.add("http://static.zuiyouxi.com/web/attached/image/20160216/20160216115111_54890.jpg");
					// imageUrls.add("http://static.zuiyouxi.com/web/attached/image/20160216/20160216115104_22429.jpg");
					banner.setImages(imageUrls);
					banner.setOnBannerClickListener(new OnBannerClickListener() {
						@Override
						public void OnBannerClick(int position) {
							position = position - 1;
							ToBannerApp(carousels.get(position).getPkg(), carousels.get(position).getVersionCode());
						}
					});

					// banner.setImageResoucesUrl(imageUrls, new
					// OnBannerImageClickListener() {
					// @Override
					// public void onImageClick(int position, String url) {
					//
					// String pkg = carousels.get(position).getPkg();
					// int versionCode =
					// carousels.get(position).getVersionCode();
					//
					// ToBannerApp(pkg, versionCode);
					// }
					// });

					// ArrayList<String> images = (ArrayList<String>)
					// AppCacheUtils.getInstance(getActivity(),
					// CACHE_BANNER).getObject(CACHE_BANNER);
					// bv_tab02_banner.setImageResoucesUrl(images,null);

					// 缓存banner地址
					AppCacheUtils.getInstance(getActivity(), CACHE_BANNER).put(CACHE_BANNER, imageUrls);

				} else {
					ToastShow.shortMessage(result.getRetMsg());
				}
			}

		});
	}

	/**
	 * 跳转到详情页面并显示轮播图的app
	 * 
	 * @param versionCode
	 * @param pkg
	 */
	private void ToBannerApp(String pkg, int versionCode) {
		if (TextUtils.isEmpty(pkg)) {
			ToastShow.shortMessage("广告页");
			return;
		}
		String json = GsonUtil.toSearchApp(pkg, versionCode);
		HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
			@Override
			public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
				super.onResponse(arg0, arg1, arg2, arg3);
				JsonDataRestult<BannerApp> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<BannerApp>>() {
				}.getType());

				if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
					if (result.getData().getApp() != null) {
						intent = new Intent(getActivity(), AppDetailActivity.class);
						intent.putExtra(Constant.DATA, result.getData().getApp());
						startActivity(intent);
					} else {
						ToastShow.shortMessage("暂无信息");
					}
				} else {
					ToastShow.shortMessage("广告页");
				}
			}

			@Override
			public void onError(boolean isFromCache, Call call, Response response, Exception e) {
				if (response == null) {
					ToastShow.shortMessage(getString(R.string.alert_failed_connect));
				}
				super.onError(isFromCache, call, response, e);
			}
		});
	}

	/**
	 * 联网获取apps信息
	 */
	private void getApps(final String sort, int page) {

		String json = GsonUtil.toQueryJson("", sort, null, null, page);
		HttpUtil.post(json, new StoreStringCallBack(getActivity()) {
			@Override
			public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
				super.onResponse(arg0, arg1, arg2, arg3);
				JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(arg1,
						new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
						}.getType());
				if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
					switch (sort) {
					case URLConstants.SORT_COMMENT:
						comment.clear();
						comment.addAll(result.getData().getApps());
						rv_comment.getAdapter().notifyDataSetChanged();
						break;
					case URLConstants.SORT_DOWNLOAD:
						download.clear();
						download.addAll(result.getData().getApps());
						rv_download.getAdapter().notifyDataSetChanged();
						break;
					case URLConstants.SORT_LATEST:
						latest.clear();
						latest.addAll(result.getData().getApps());
						rv_latest.getAdapter().notifyDataSetChanged();
						break;
					}
					pagerAdapter.notifyDataSetChanged();

				} else {

					ToastShow.shortMessage(result.getRetMsg());
				}
				// TODO loading控件消失
				loading.setAnimation(out);
				loading.setVisibility(View.GONE);
				stopRefresh();
			}

			@Override
			public void onError(boolean isFromCache, Call call, Response response, Exception e) {
				loading.setAnimation(out);
				loading.setVisibility(View.GONE);
				super.onError(isFromCache, call, response, e);

				stopRefresh();

			}

		});
	}

	/**
	 * 停止
	 */
	private void stopRefresh() {
		if (swipe_refresh == null) {
			return;
		}
		if (swipe_refresh.isRefreshing()) {
			swipe_refresh.setRefreshing(false);
		}
	}

	/**
	 * 更新
	 */
	public void refresh() {
		if (rv_latest.getAdapter() != null) {
			rv_latest.getAdapter().notifyDataSetChanged();
		}
		if (rv_download.getAdapter() != null) {
			rv_download.getAdapter().notifyDataSetChanged();
		}
		if (rv_comment.getAdapter() != null) {
			rv_comment.getAdapter().notifyDataSetChanged();
		}
		if (pagerAdapter != null) {
			pagerAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 初始化tablayout
	 */
	private void initTabLayout(View view) {
		tabLayout = (TabLayout) view.findViewById(R.id.tab02_tablayout);
		tabLayout.setupWithViewPager(viewPager);
	}

	/**
	 * 初始化recyclerview
	 * 
	 * @param view
	 */
	private void initRecyclerView(View view) {
		rv_latest = new RecyclerView(getContext());
		rv_download = new RecyclerView(getContext());
		rv_comment = new RecyclerView(getContext());

		setRecyclerAdapter(rv_latest, latest);
		setRecyclerAdapter(rv_download, download);
		setRecyclerAdapter(rv_comment, comment);
	}

	/**
	 * 初始化recycler
	 */
	private void initViewPager(View view) {
		viewPager = (ViewPager) view.findViewById(R.id.tab02_viewpager);

		pagerAdapter = new PagerAdapter() {
			@Override
			public Object instantiateItem(ViewGroup container, int position) {

				switch (position) {
				case 0:
					container.addView(rv_latest);
					return rv_latest;
				case 1:
					container.addView(rv_download);
					return rv_download;
				case 2:
					container.addView(rv_comment);
					return rv_comment;

				default:
					break;
				}

				RecyclerView recyclerView = new RecyclerView(getContext());

				// switch (position) {
				// case 0:
				// setRecyclerAdapter(recyclerView, latest);
				// break;
				// case 1:
				// setRecyclerAdapter(recyclerView, download);
				// break;
				// case 2:
				// setRecyclerAdapter(recyclerView, comment);
				// break;
				//
				// default:
				// break;
				// }

				return recyclerView;
			}

			@Override
			public CharSequence getPageTitle(int position) {
				return tabName[position];
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public void destroyItem(ViewGroup container, int position, Object object) {
				// super.destroyItem(container, position, object);
				// TODO viewpager页面销毁
				((ViewPager) container).removeView((View) object);
			}

			@Override
			public int getCount() {
				return tabName.length;
			}

			@Override
			public int getItemPosition(Object object) {
				// return super.getItemPosition(object);
				return POSITION_NONE;
			}
		};
		viewPager.setAdapter(pagerAdapter);
	}

	/**
	 * 设置recyclerview的adapter
	 * 
	 * @param recyclerView
	 * @param list
	 */
	private void setRecyclerAdapter(RecyclerView recyclerView, final List<AppModel> list) {
		recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
		adapter = new CommonAdapter<AppModel>(getContext(), R.layout.item_app, list) {
			@Override
			protected void convert(ViewHolder holder, AppModel t, int position) {
				final AppModel app = list.get(position);
				// holder.setImageDrawable(R.id.iv_item_app_icon,
				// app.getLocalIcon());
				ImageView iv = holder.getView(R.id.iv_item_app_icon);
				ImageLoader.getInstance().displayImage(app.getIconUrl(), iv);
				holder.setText(R.id.tv_item_app_name, app.getAppName());
				holder.setRating(R.id.ratingbar_item_app_score, app.getScore());
				holder.setText(R.id.tv_item_app_total_size, Util.byte2Mega(app.getSize()));
				holder.setText(R.id.tv_item_app_version_name, app.getRemoteVersionName());

				final DownloadInfo downloadInfo = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());

				// ****************************判断app安装状态
				// if (ApkUtils.isInstalled(getActivity(), app.getAppPackName(),
				// app.getRemoteVersionCode())) {
				// holder.setText(R.id.btn_item_app_install, "打开");
				// }else if (ApkUtils.isAvailable(getActivity(),
				// app.getAppPackName())) {
				// holder.setText(R.id.btn_item_app_install, "更新");
				// }else if(downloadInfo != null && downloadInfo.getState() ==
				// DownloadManager.FINISH) {
				// if (ApkUtils.isExist(downloadInfo.getTargetPath())) {
				// holder.setText(R.id.btn_item_app_install, "安装");
				// }else {
				// holder.setText(R.id.btn_item_app_install, "下载");
				// }
				// }else {
				// holder.setText(R.id.btn_item_app_install, "下载");
				// }

				if (downloadInfo != null && downloadInfo.getState() == DownloadManager.FINISH) {
					if (ApkUtils.isInstalled(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
						holder.setText(R.id.btn_item_app_install, "打开");
					} else if (ApkUtils.isAvailable(getActivity(), app.getAppPackName())) {
						holder.setText(R.id.btn_item_app_install, "更新");
					} else {
						if (FileUtils.isExist(downloadInfo.getTargetPath())) {
							holder.setText(R.id.btn_item_app_install, "安装");
						} else {
							holder.setText(R.id.btn_item_app_install, "下载");
						}
					}
				} else {
					holder.setText(R.id.btn_item_app_install, "下载");
				}

				final View button = holder.getView(R.id.btn_item_app_install);

				holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {
					@Override
					public void onClick(View v) {
						DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
						// 如果该任务的状态为完成
						if (info != null && info.getState() == DownloadManager.FINISH) {
							// 如果已经安装则打开; 未安装,判断安装包是否存在. 如果存在则安装, 不存在则重新下载;
							// if (ApkUtils.isAvailable(getContext(),
							// app.getAppPackName())) {
							if (ApkUtils.isInstalled(getActivity(), app.getAppPackName(), app.getRemoteVersionCode())) {
								if (!app.getAppPackName().equals(Util.getPackageName(getActivity()))) {
									/*ApkUtils.openAPP(getActivity(), app.getAppPackName());*/
									//------------------
									if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
										ApkUtils.openAPP(getContext(), app.getAppPackName());
									} else {//无图标打开方式
										//ApkUtils.openDefaultApp(getActivity(),app.getAppPackName());
										ApkUtils.openAPP(getContext(), app.getAppPackName(), app.getActivity());
									}
								}
							} else {
								if (FileUtils.isExist(info.getTargetPath())) {
									// TODO 安装
									ApkUtils.installSilent(getActivity(), new File(info.getTargetPath()));
									// ApkUtils.install(getActivity(), new
									// File(info.getTargetPath()));
								} else {
									APPDownloadManager.removeTask(info.getTaskKey());
									APPDownloadManager.addTask(getActivity(), app, info.getListener());
									// TODO 点击下载后跳转到下载列表页面吗?
									// startActivity(AppDownManagerActivity1.class);
									SnackbarUtil.showSnackbar(getActivity(), button);
								}
							}
						} else {
							APPDownloadManager.addTask(getActivity(), app, null);
							// TODO 点击下载后跳转到下载列表页面吗?
							// startActivity(AppDownManagerActivity1.class);
							SnackbarUtil.showSnackbar(getActivity(), button);
						}
					}

					// private void showSnackbar(final View button) {
					// Snackbar snackbar = Snackbar.make(button, "已添加到下载列表",
					// 3000);
					// View snackbarView = snackbar.getView();
					// if(snackbarView!=null){
					// ((TextView)
					// snackbarView.findViewById(R.id.snackbar_text)).setTextColor(Color.WHITE);//获取Snackbar的message控件，修改字体颜色
					// }
					// snackbar.setAction("查看", new OnClickListener() {
					// @Override
					// public void onClick(View v) {
					// startActivity(AppDownManagerActivity1.class);
					// }
					// }).show();
					// }
				});
				/*
				 * 
				 * refresh(info, app, holder);
				 */
			}
		};

		adapter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
				intent = new Intent(getActivity(), AppDetailActivity.class);
				AppModel app = list.get(position);
				intent.putExtra(Constant.DATA, app);
				startActivity(intent);
			}

			@Override
			public boolean onItemLongClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder,
					int position) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		recyclerView.setAdapter(adapter);
	}

	/**
	 * 更新 暂无用
	 * 
	 * @param info
	 * @param app
	 * @param holder
	 */
	// protected void refresh(final DownloadInfo info, final AppModel app, final
	// ViewHolder holder) {
	//
	// DownloadListener listener = new MyDownloadListener();
	// listener.setUserTag(holder);
	//
	// if (info != null) {
	// info.setListener(listener);
	// }
	//
	// switch (info.getState()) {
	// case DownloadManager.NONE:
	// holder.setText(R.id.btn_item_app_install, "安装");
	// break;
	// case DownloadManager.WAITING:
	// holder.setText(R.id.btn_item_app_install, "准备");
	// break;
	// case DownloadManager.DOWNLOADING:
	// holder.setText(R.id.btn_item_app_install, "准备");
	// break;
	// case DownloadManager.PAUSE:
	// holder.setText(R.id.btn_item_app_install, "暂停");
	// break;
	// case DownloadManager.FINISH:
	// holder.setText(R.id.btn_item_app_install, "安装");
	// ApkUtils.isAvailable(getContext(), app.getAppPackName());
	// break;
	// case DownloadManager.ERROR:
	//
	// break;
	//
	// default:
	// break;
	// }
	//
	// holder.setOnClickListener(R.id.btn_item_app_install, new
	// OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// if (info != null && info.getState() == DownloadManager.FINISH) {
	// ApkUtils.install(getContext(), new File(info.getTargetPath()));
	// }else {
	// GetRequest request = new GetRequest(Util.getDownloadUrl(info.getUrl()));
	// DownloadListener listener = new MyDownloadListener();
	// listener.setUserTag(holder);
	// DownloadService.getDownloadManager().addTask(app.getAppName(),
	// app.getUrl(), request, listener);
	// startActivity(AppDownManagerActivity1.class);
	// }
	// }
	// });
	// }

	/**
	 * 
	 * @author cxy
	 *
	 */
	// class MyDownloadListener extends DownloadListener{
	//
	// @Override
	// public void onProgress(DownloadInfo downloadInfo) {
	// if (getUserTag() == null) {
	// return;
	// }
	// ViewHolder holder = (ViewHolder) getUserTag();
	// AppModel app = (AppModel)
	// AppCacheUtils.getInstance(getContext()).getObject(downloadInfo.getTaskKey());
	// refresh(downloadInfo, app, holder);
	// }
	//
	// @Override
	// public void onFinish(DownloadInfo downloadInfo) {
	// }
	//
	// @Override
	// public void onError(DownloadInfo downloadInfo, String errorMsg, Exception
	// e) {
	// }
	//
	// }

	/**
	 * 是否显示refresh
	 * 
	 * @param b
	 */
	private void showRefresh(final boolean b) {
		swipe_refresh.post(new Runnable() {
			@Override
			public void run() {
				swipe_refresh.setRefreshing(b);
			}
		});
	}
}
